/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weiyi.chat.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.weiyi.chat.R;
import com.weiyi.chat.api.ILogin;
import com.weiyi.chat.common.Constant;
import com.weiyi.chat.common.DemoHelper;
import com.weiyi.chat.common.base.BaseActivity;
import com.weiyi.chat.db.DemoDBManager;
import com.weiyi.chat.domain.User;
import com.weiyi.chat.presenter.LoginPresenter;
import com.weiyi.chat.utils.CountDownTimerUtils;
import com.weiyi.chat.utils.MyReusouce;
import com.weiyi.chat.utils.PreferenceUtil;
import com.weiyi.chat.utils.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Login screen
 *
 */
public class LoginActivity extends BaseActivity implements ILogin.Views {
    private static final String TAG = "LoginActivity";
    public static final int REQUEST_CODE_SETNICK = 1;
    @BindView(R.id.iv_username)
    ImageView mIvUsername;
    @BindView(R.id.username)
    EditText mUsername;
    @BindView(R.id.iv_password)
    ImageView mIvPassword;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.rl_password)
    RelativeLayout mRlPassword;
    @BindView(R.id.btn_register)
    Button mBtnRegister;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    @BindView(R.id.switch_login_way)
    TextView mSwitchLoginWay;
    @BindView(R.id.reset_psw)
    TextView mResetPsw;
    @BindView(R.id.sms_code)
    CheckedTextView mSmsCode;

    private boolean progressShow;
    private boolean autoLogin = false;
    private LoginPresenter mLoginPresenter;
    private boolean mSmsLigin = false;

    private CountDownTimerUtils mCountDownTimerUtils;

    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {
            return;
        }
        String account = (String) PreferenceUtil.getValue("register_account", mAct);
        if (!TextUtils.isEmpty(account)){
            mUsername.setText(account);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mCountDownTimerUtils != null) {
            mCountDownTimerUtils.cancel();
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.em_activity_login;
    }

    @Override
    protected void initView() {

        mLoginPresenter = new LoginPresenter(this);

        //        if (DemoHelper.getInstance().isLoggedIn()) {
        if (PreferenceUtil.getValueB(Constant.SP_ISLOGIN, false, mAct)) {
            autoLogin = true;
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            return;
        }

        // if user changed, clear the password
        mUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mPassword.setText(null);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN))) {
                    login();
                    return true;
                } else {
                    return false;
                }
            }
        });

        if (DemoHelper.getInstance().getCurrentUsernName() != null) {
            mUsername.setText(DemoHelper.getInstance().getCurrentUsernName());
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onLoginSucess(final User userBean) {
        // After logout，the DemoDB may still be accessed due to async callback, so the DemoDB will be re-opened again.
        // close it before login to make sure DemoDB not overlap
        DemoDBManager.getInstance().closeDB();
        // reset current user name before login
        DemoHelper.getInstance().setCurrentUserName(userBean.getBody().getData().getBus_mobile());

        final long start = System.currentTimeMillis();
        // call login method
        Log.d(TAG, "EMClient.getInstance().login");
        EMClient.getInstance().login(userBean.getBody().getData().getBus_mobile(), "123465", new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.d(TAG, "login: onSuccess");
                // ** manually load all local groups and conversation
//                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();

                // update current user's display name for APNs
                boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(
                        userBean.getBody().getData().getBus_owner());
                if (!updatenick) {
                    Log.e("LoginActivity", "update current user nick fail");
                }
                // get user's info (this should be get from App's server or 3rd party service)
                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
            }

            @Override
            public void onProgress(int progress, String status) {
                Log.d(TAG, "login: onProgress");
            }

            @Override
            public void onError(final int code, final String message) {
                Log.d(TAG, "login: onError: " + code);
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + message,
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

        PreferenceUtil.setEditB(Constant.SP_ISLOGIN, true, mAct);
        String info_avatar_origin = MyReusouce.BASE_URL + userBean.getBody().getData().getBus_info().getInfo_avatar_origin();
        PreferenceUtil.setEdit(Constant.SP_USER_AVATAR, TextUtils.isEmpty(info_avatar_origin) ? Constant.DEFAULT_AVATAR_VALUE : info_avatar_origin, mAct);
        if (Integer.valueOf(userBean.getBody().getData().getBus_id()) > 20){
            PreferenceUtil.setEditB(Constant.SP_ISADMIN, false, mAct);
        }else{
            PreferenceUtil.setEditB(Constant.SP_ISADMIN, true, mAct);
        }
        String bus_owner = userBean.getBody().getData().getBus_owner(); //真是姓名
        String info_name = userBean.getBody().getData().getBus_info().getInfo_name(); //昵称
        String info_tel = userBean.getBody().getData().getBus_info().getInfo_tel(); //固话
        String info_intro = userBean.getBody().getData().getBus_info().getInfo_intro();//店铺介绍
        String nick = TextUtils.isEmpty(info_name) ? bus_owner : info_name;
        PreferenceUtil.setEdit(Constant.SP_BUS_OWNER, nick, mAct);
        DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(nick);
        EMClient.getInstance().updateCurrentUserNick(nick);
        EMClient.getInstance().pushManager().updatePushNickname(nick);

        PreferenceUtil.setEdit(Constant.SP_BUS_ID, userBean.getBody().getData().getBus_id(), mAct);
        PreferenceUtil.setEdit(Constant.SP_BUS_MOBILE, userBean.getBody().getData().getBus_mobile(), mAct);
        PreferenceUtil.setEdit(Constant.SP_BUS_OWNER_ID_NUMBER, userBean.getBody().getData().getBus_owner_id_number(), mAct);
        PreferenceUtil.setEdit(Constant.SP_TOKEN, userBean.getBody().getData().getToken(), mAct);
        PreferenceUtil.setEdit(Constant.SP_INFO_TEL, TextUtils.isEmpty(info_tel) ? "" : info_tel, mAct);
        PreferenceUtil.setEdit(Constant.SP_INFO_INTRO, TextUtils.isEmpty(info_intro) ? "" : info_intro, mAct);

        Intent intent = new Intent(mAct, MainActivity.class);

        startActivity(intent);
        finish();
    }

    @Override
    public void onRequestSmsSucess() {
        mCountDownTimerUtils = new CountDownTimerUtils(mSmsCode, 60000, 1000);
        mCountDownTimerUtils.start();
    }

    @Override
    public void showError(String msg) {
        ToastUtil.showTextToast(mAct, msg);
    }

    @OnClick({R.id.btn_register, R.id.btn_login, R.id.switch_login_way, R.id.reset_psw})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                startActivityForResult(new Intent(this, RegisterActivity.class), 0);
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.reset_psw:

                startActivity(new Intent(mAct, ComeBackPswActivity.class));

                break;
            case R.id.switch_login_way:

//                mSmsLigin = !mSmsLigin;
//                ObjectAnimator visToInvis = ObjectAnimator.ofFloat(mRlPassword, "rotationX", 0f, 360f);
//                visToInvis.addListener(new AnimatorListenerAdapter() {
//                    @Override
//                    public void onAnimationStart(Animator animation) {
//                        super.onAnimationStart(animation);
//                        if (mSmsLigin){
//                            mIvPassword.setVisibility(View.GONE);
//                        }else{
//                            mIvPassword.setVisibility(View.VISIBLE);
//                        }
//                    }
//
//                    @Override
//                    public void onAnimationEnd(Animator animation) {
//                        super.onAnimationEnd(animation);
//                        if (mSmsLigin){
//                            mSmsCode.setVisibility(View.VISIBLE);
//                            mSwitchLoginWay.setText("密码登录");
//                            ToastUtil.showTextToast(mAct, "验证码登录");
//                        }else{
//                            mSmsCode.setVisibility(View.GONE);
//                            mSwitchLoginWay.setText("验证码登录");
//                            ToastUtil.showTextToast(mAct, "密码登录");
//                        }
//                    }
//                });
//                visToInvis.start();
                break;
        }
    }

    /**
     * login
     */
    public void login() {
        if (!EaseCommonUtils.isNetWorkConnected(this)) {
            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
            return;
        }
        String currentUsername = mUsername.getText().toString().trim();
        String currentPassword = mPassword.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, R.string.User_name_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, R.string.Password_cannot_be_empty, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mSmsLigin){
            mLoginPresenter.smsLogin(currentUsername, currentPassword);
        }else{
            mLoginPresenter.pswLogin(currentUsername, currentPassword);
        }
    }
}
